package cn.edu.nju.gitlab.presenter;

import java.util.List;

import cn.edu.nju.gitlab.data.TeacherData;
import cn.edu.nju.gitlab.model.Exam;
import cn.edu.nju.gitlab.fragment.ExerciseListFragment;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by lpt on 2017/6/12.
 */

public class ExerciseListPresenter  {
    private Subscription subscription;
    private TeacherData repository;
    private ExerciseListFragment view;

    public ExerciseListPresenter(ExerciseListFragment view, TeacherData repository) {
        this.repository = repository;
        this.view = view;
    }

    public void getExercise(String username, String password, int courseId) {
        subscription = repository.getExercise(username, password, courseId)
                .subscribeOn(Schedulers.io())
                .onErrorReturn(new Func1<Throwable, List<Exam>>() {
                    @Override
                    public List<Exam> call(Throwable throwable) {
                        throwable.printStackTrace();
                        view.showError();
                        return null;
                    }
                })
                .subscribe(new Action1<List<Exam>>() {
                    @Override
                    public void call(List<Exam> groups) {
                        if (groups != null) {
                            view.showList(groups);
                        }
                    }
                });
    }



    public void onStop() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }

}
